////////////////////////////////////
// Author:Nemo                    //
// email: captain.nemon@gmail.com //
// homepage:AsynSyn.googlecode.com //
////////////////////////////////////

//同步队列对象管理器
var SynchronizationQueueManger={
	//同步队列对象数组
	SynchronizationQueues:{},
	//获得/创建一个同步队列对象
	GetTheSynchronizationQueue:function(sQName) {
	   if (!this.SynchronizationQueues)this.SynchronizationQueues=new Object();
	   if (!sQName)sQName="default";
	   if (!SynchronizationQueueManger.SynchronizationQueues.hasOwnProperty(sQName)){
			function TheQ(sName){
				this.name =sName;
				this.Tasks =[];
				this.currentTask=-1;
				this.nextTask =-1;
				this.stat =-1;// -1 初始未运行 ; 0 队列运行中 ; 1 异步运行中 ;2 暂停 ;3 已停止 
			};
			//doNothing
			TheQ.prototype.doNothing=function(){}
			//add a task
			TheQ.prototype.add = function( fTaskHandler , aTaskVars , fTaskRuturnHandler){
				this.Tasks.push({TaskHandler:fTaskHandler , TaskVars:aTaskVars , TaskRuturnHandler:fTaskRuturnHandler });
			}
			//run the No.index task
			TheQ.prototype.start =  function( ){
				this.currentTask=0;
				//for(var i=0;i<this.Tasks.length;i++){
				//	alert(this.Tasks[i].TaskVars);
				//}
				var tmpTask=this.Tasks[this.currentTask];
				tmpTask.TaskHandler.apply(null,tmpTask.TaskVars);
			};
			//for user use to handle the Asynchronous object return
			TheQ.prototype.RuturnHandler = function( args){
				var tmpTask=this.Tasks[this.currentTask];
				tmpTask.TaskRuturnHandler.apply(null,args);
				this.currentTask=this.currentTask+1;
				if(this.currentTask<this.Tasks.length ){
					tmpTask=this.Tasks[this.currentTask];
					tmpTask.TaskHandler.apply(null,tmpTask.TaskVars);
				}else{
					//this.currentTask=-1;
					this.stat=3;
				}
			};

			// friend event
			TheQ.prototype.onBeforTaskStart   =TheQ.prototype.doNothing;
			TheQ.prototype.onAfterTaskFinished=TheQ.prototype.doNothing;
			TheQ.prototype.raiseEvent = function(eventName,vars){
					if (eventName="onBeforTaskStart" && this.onBeforTaskStart.prototype.constructor ==Function){
						this.onBeforTaskStart(vars);
					}else if(eventName="onAfterTaskFinished" && this.onAfterTaskFinished.prototype.constructor ==Function){
						this.onAfterTaskFinished(vars);
					}else{
						this.doNothing();
					}
			}
			
			//set SynchronizationQueue
			this.SynchronizationQueues[sQName]=new TheQ(sQName);
		}
		return this.SynchronizationQueues[sQName];
	},
	//获得同步队列处理句柄
	onRuturnHandler:function(sQName) {
       var name=sQName;
	   return function(){
			var args=[];
			for(var i=0;i<arguments.length;i++){
				args.push(arguments[i]);
			}
			SynchronizationQueueManger.GetTheSynchronizationQueue(name).RuturnHandler(args);
		}
	}
}